//互斥量的用法
#include <iostream> 
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

int sum = 0; // 定义了一个全局变量，让所有的线程进行访问，这样就会出现同时写的情况，势必会需要锁机制；
pthread_mutex_t sum_mutex;

void* say_hello(void* args) {
	cout << "hello in thread " << *((int *)args) << endl;
	pthread_mutex_lock (&sum_mutex); //修改sum 就先加锁，锁被占用就阻塞，直到拿到锁再修改sum
	cout << "before sum is " << sum << " in thread" << *((int *)args) << endl;
	sum += *((int *)args);
	cout << "after sum is " << sum << " in thread" << *((int *)args) << endl;
	pthread_mutex_unlock (&sum_mutex); // 完事后解锁，释放给其他线程用

	pthread_exit(0);
}

int main() {
	pthread_t tids[NUM_THREADS];
	int indexes[NUM_THREADS];
	pthread_attr_t attr;
	pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	pthread_mutex_init (&sum_mutex, NULL); // 对锁的初始化

	for (int i = 0; i < NUM_THREADS; ++i) {
		indexes[i] = i;
		int ret = pthread_create(&tids[i], &attr, say_hello, (void *) &(indexes[i]));
		if (ret != 0) {
			cout << "pthread_create error: error_code=" << ret << endl;
		}
	}

	pthread_attr_destroy(&attr);

	void *status;
	for (int i = 0; i < NUM_THREADS; ++i) {
		int ret = pthread_join(tids[i], &status);
		if (ret != 0) {
			cout << "pthread_join error: error_code=" << ret << endl;
		}
	}

	cout << "finally sum is" << sum << endl;

	pthread_mutex_destroy(&sum_mutex); //注销锁
}